<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        noimmediate
        @submit="submit"
        @reset="handleReset"
      />
    </Container>
    <Container height="fill" display="flexY">
      <OperationContainer style="margin-bottom: 10px">
        <Button icon="add" @click="insert">新建</Button>
        <Button icon="" @click="exportData">导出</Button>
      </OperationContainer>
      <Table
        :data="tableData"
        :pagination="pagination"
        :loading="tableLoading"
        :columns="tableDataEL"
        border
        @paginationChange="paginationChange"
        @rowSelection="rowSelection"
      >
        <template #action="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <i class="el-icon-edit action" @click="edit(scope.row)" />
            <!-- <i class="el-icon-edit action" /> -->
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <i class="el-icon-delete action" @click="remove(scope.row)" />
            <!-- <i class="el-icon-delete action" /> -->
          </el-tooltip>
        </template>
      </Table>
      <Drawer
        :visible="drawerVisible"
        :title="drawerTitle"
        :footer-btns="drawerController"
        width="30%"
        @cancel="drawerCancel"
        @submit="drawerSubmit"
        @continueAdd="continueAdd"
      >
        <div class="draw-body">
          <el-switch
            v-model="mode"
            active-text="扫码输入"
            inactive-text="手动输入"
            style="margin-bottom: 22px"
          />
          <el-form
            ref="formData"
            label-width="80px"
            :model="formData"
            :rules="rules"
            @keyup.enter.native="drawerSubmit('formData')"
          >
            <el-form-item label="票据代码" prop="ticketCode">
              <!-- oninput="value=value.replace(/[^\d.]/g,'')" -->
              <el-input
                ref="ticketCode"
                :value="formData.ticketCode"
                style="width: 240px"
                size="small"
                @input="inputInput"
              />
            </el-form-item>

            <!-- oninput="value=value.replace(/[^\d.]/g,'')" -->
            <el-form-item label="票据号码" prop="ticketNumber">
              <el-input
                v-model="formData.ticketNumber"
                style="width: 240px"
                oninput="value"
                size="small"
              />
            </el-form-item>

            <el-form-item label="检验码" prop="checkCode">
              <el-input
                v-model="formData.checkCode"
                style="width: 240px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="开票日期" prop="billingDate">
              <el-date-picker
                v-model="formData.billingDate"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
                style="width: 280px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="金额" prop="money">
              <el-input
                v-model="formData.money"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                style="width: 240px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="报销人" prop="reimbursementPerson">
              <el-input
                v-model="formData.reimbursementPerson"
                style="width: 240px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="流程号" prop="processNumber">
              <el-input
                v-model="formData.processNumber"
                style="width: 240px"
                size="small"
              />
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                style="width: 240px"
                size="small"
                type="textarea"
              />
            </el-form-item>
          </el-form>
        </div>
      </Drawer>
      <Dialog
        :title="dialogTitle"
        :visible="dialogVisible"
        :footer-btns="dialogController"
        @cancel="dialogCancel"
      >
        <iframe class="frame" :src="attachmentSrc" />
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import baseFilterTable from '@/utils/mixins/baseFilterTable'
import baseInfo from '../../utils/config'
import {
  findPage,
  saveOrUpdate,
  remove,
  download
} from '@/utils/apis/invoiceSystem/register'
import Container from '../../components/Container.vue'

export default {
  name: '',
  components: { Container },
  mixins: [baseFilterTable],
  data() {
    return {
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      rules: {
        ticketCode: [
          { required: true, message: '请输入票据代码', trigger: 'change' }
        ],
        ticketNumber: [
          { required: true, message: '请输入票据号码', trigger: 'change' }
        ],
        checkCode: [
          { required: true, message: '请输入检验码', trigger: 'change' }
        ],
        // billingDate: [
        //   { required: true, message: '请选择开票日期', trigger: 'change' }
        // ],
        money: [{ required: true, message: '请输入金额', trigger: 'change' }]
      },
      formData: {
        money: '',
        billingDate: '',
        checkCode: '',
        ticketNumber: '',
        ticketCode: '',
        remark: '',
        processNumber: '',
        reimbursementPerson: ''
      },
      basePageConfig: {
        searchBarShow: true
      },
      form: {
        noteCode: ''
      },
      elements: [
        {
          label: '票据代码',
          type: 'Input',
          format: ' ',
          key: 'ticketCode',
          value: ''
        },
        {
          label: '票据号码',
          type: 'Input',
          format: ' ',
          key: 'ticketNumber',
          value: ''
        },
        {
          label: '流程号',
          type: 'Input',
          format: ' ',
          key: 'processNumber',
          value: ''
        },
        {
          label: '金额',
          type: 'Input',
          format: ' ',
          key: 'money',
          value: ''
        },
        {
          label: '报销人',
          type: 'Input',
          format: ' ',
          key: 'reimbursementPerson',
          value: ''
        }
        // ,
        // {
        //   label: '开票日期',
        //   type: 'DatePicker',
        //   format: 'yyyy-MM-dd',
        //   key: 'uploadTime',
        //   mode: 'daterange',
        //   value: ''
        // }
      ],
      tableData: [],
      tableDataEL: [
        // {
        //   dataIndex: 'ticketCode',
        //   title: '',
        //   width: 55,
        //   type: 'selection'
        // },
        {
          dataIndex: 'ticketCode',
          title: '票据代码',
          width: 180
        },
        {
          dataIndex: 'ticketNumber',
          title: '票据号码',
          width: 120
        },
        {
          dataIndex: 'checkCode',
          title: '检验码',
          width: 120
        },
        {
          dataIndex: 'billingDate',
          title: '开票日期',
          width: 120
        },
        {
          dataIndex: 'money',
          title: '金额',
          width: 120,
          align: 'right'
        },
        {
          dataIndex: 'reimbursementPerson',
          title: '报销人',
          width: 120
        },
        {
          dataIndex: 'processNumber',
          title: '流程号',
          width: 120
        },
        {
          dataIndex: 'remark',
          title: '备注',
          type: ''
        },
        {
          dataIndex: 'createTime',
          title: '录入日期',
          width: 170
        },
        {
          dataIndex: 'createBy',
          title: '录入人',
          width: 120
        },
        {
          dataIndex: 'action',
          title: '操作',
          align: 'center',
          type: 'otherTag',
          width: 180
        }
      ],
      drawerController: [
        {
          text: '提交',
          trigger: 'submit',
          type: 'primary'
        }
      ],
      dialogController: [
        {
          text: '取消',
          trigger: 'cancel'
        }
      ],
      attachmentSrc: '',
      dropList: [
        {
          label: '批量导出',
          value: '1',
          handlerClick: this.exportSelect
        },
        {
          label: '全部导出',
          value: '2',
          handlerClick: this.exportAll
        }
      ],
      dropDownLoading: false,
      drawerVisible: false,
      imgList: [],
      currentId: '',
      isEdit: false,
      multipleSelection: [],
      mode: true, // 切换手动输入 -> false 还是 扫码输入 -> true
      timer: '', // 节流参数
      throttle: 1000 // 节流时间
    }
  },
  created() {
    this.getData()
  },
  methods: {
    handleReset() {
      // 重置
    },
    rowSelection(data) {
      this.multipleSelection = data
    },
    exportData() {
      download({}).then((res) => {
        if (res.status === 200) {
          const blob = new Blob([res.data], {
            type: res.data.type + 'charset=utf-8'
          })
          const downloadLink = document.createElement('a')
          const URL = window.URL || window.webkitURL || window.moxURL
          const downUrl = URL.createObjectURL(blob)
          downloadLink.href = downUrl
          downloadLink.download = '发票列表.xls'
          downloadLink.click()
          window.URL.revokeObjectURL(downUrl)
        }
      })
    },
    continueAdd() {
      // 继续提交
    },
    submit(val) {
      this.pagination.pageNum = 1
      this.getData(val)
    },

    paginationChange(val) {
      this.pagination.pageNum = val.current
      this.pagination.pageSize = val.pageSize
      this.getData()
    },
    handleNodeClick() {},
    getData(val) {
      console.log(val)
      const params = {
        num: this.pagination.pageNum,
        size: this.pagination.pageSize,
        ticketCode: val ? val.ticketCode : '',
        ticketNumber: val ? val.ticketNumber : '',
        processNumber: val ? val.processNumber : '',
        money: val ? val.money : null,
        // startTime: this.elements[4].value ? this.elements[4].value[0] + ' ' + '00:00:00' : '',
        // endTime: this.elements[4].value ? this.elements[4].value[1] + ' ' + '00:00:00' : '',
        reimbursementPerson: val ? val.reimbursementPerson : ''
      }

      findPage(params).then((res) => {
        console.log(res)
        if (res.data.code === 200) {
          this.tableData = res.data.data.list
          this.pagination.total = res.data.data.total
        } else {
          this.$message.warning(res.data.msg)
          console.log('g')
        }
      })
    },
    insert() {
      this.$refs.formData.resetFields()
      this.isEdit = false
      this.drawerTitle = '新增'
      this.drawerVisible = true
      this.setFocus()
    },
    edit(row) {
      this.isEdit = true
      this.currentId = row.id
      this.drawerTitle = '编辑'
      this.drawerVisible = true
      this.formData = JSON.parse(JSON.stringify(row))
      this.setFocus()
    },
    // 设置聚焦
    setFocus() {
      this.$nextTick(() => {
        this.$refs.ticketCode.$el.children[0].focus()
      })
    },
    // 扫描结果填充
    inputInput(val) {
      if (this.mode) {
        this.formData.ticketCode = val
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          if (val !== '') {
            if (val.indexOf('/') > -1) {
              if (val.split('').filter((k) => k === '/').length >= 3) {
                const res = val.split('/').splice(-3, 3)
                const temp = []
                // res.forEach(item => {
                //   if (isNaN(parseInt(item))) {
                //     temp.push(false)
                //   }
                // })
                if (!temp.length) {
                  this.formData.ticketCode = res[0]
                  this.formData.ticketNumber = res[1]
                  this.formData.checkCode = res[2]
                }
              }
            } else {
              const res = val.split(',')
              const temp = []
              if (!temp.length) {
                debugger
                  this.formData.ticketCode = res[2]
                  this.formData.ticketNumber = res[3]
                  this.formData.checkCode = res[4]
                  this.formData.billingDate = res[5].substr(0,4)+'-'+res[5].substr(4,2)+'-'+res[5].substr(6,7)
                  this.formData.money = res[6]
                }
            }
          }
        }, this.throttle)
      } else {
        // this.formData.ticketCode = val.replace(/[^\d.]/g, '')
        this.formData.ticketCode = val
      }
    },
    remove(row) {
      this.$confirm({
        content: '请输入“立即删除”，确认删除',
        title: '提示',
        action: 'delete',

        okFn: async (res) => {
          const params = {
            id: row.id
          }

          remove(params).then((res) => {
            if (res.data.code === 200) {
              this.$message.success('删除成功')
              this.getData()
            } else {
              this.$message.warning(res.data.msg)
            }
          })

          console.log(params)
        },
        cancelFn: (res) => {
          console.log('取消')
        }
      })
    },
    showAttachment(item) {
      this.dialogTitle = item.fileName
      this.attachmentSrc = `${baseInfo.BASE_URL}upload/${item.fileUrl}`
      if (
        item.fileName.indexOf('.xlsx') === -1 &&
        item.fileName.indexOf('.xls') === -1
      ) {
        this.dialogVisible = true
      }
    },
    drawerSubmit() {
      const params = {
        ticketCode: this.formData.ticketCode,
        ticketNumber: this.formData.ticketNumber,
        checkCode: this.formData.checkCode,
        billingDate: this.formData.billingDate,
        money: this.formData.money,
        reimbursementPerson: this.formData.reimbursementPerson,
        processNumber: this.formData.processNumber,
        remark: this.formData.remark
      }
      console.log(this.formData.billingDate)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            params.id = this.currentId
            params.billingDate = params.billingDate + ' '
            saveOrUpdate(params).then((res) => {
              if (res.data.code === 200) {
                this.$message.success('修改成功')
                this.getData()
                this.drawerVisible = false
              } else {
                this.$message.warning(res.data.msg)
                this.drawerVisible = false
              }
            })
          } else {
            saveOrUpdate(params).then((res) => {
              if (res.data.code === 200) {
                this.$message.success('新增成功')
                this.getData()
                this.$refs.formData.resetFields()
                this.setFocus()
                // this.drawerVisible = false
              } else {
                this.$confirm({
                  content: `${res.data.message}`,
                  title: '异常提醒'
                })
                this.drawerVisible = false
              }
            })
          }
        } else {
          return false
        }
      })
    },
    dialogCancel() {
      this.dialogVisible = false
    },
    success(res) {
      this.$message.success('提交成功')
      this.$btnLoading('drawerController', 'submit', false)
      this.drawerCancel()
    },
    fail(res) {
      this.$message.error('提交失败')
      this.$btnLoading('drawerController', 'submit', false)
    },
    exportSelect() {
      console.log('批量导出')
      this.dropDownLoading = true
      setTimeout(() => {
        this.dropDownLoading = false
      }, 1000)
    },
    exportAll() {
      console.log('全部导出')
      this.dropDownLoading = true
      setTimeout(() => {
        this.dropDownLoading = false
      }, 1000)
    },
    async fileDel(item, index) {},
    drawerCancel() {
      this.drawerVisible = false
      this.imgList = []
      this.getData()
    }
  }
}
</script>

<style lang="less" scoped>
.input-item {
  margin-bottom: 20px;
}
.control-box {
  margin-bottom: 10px;
  display: flex;
}
.action {
  font-size: 16px;
  margin-right: 8px;
  cursor: pointer;
  color: #2165f9;
}
.action:last-of-type {
  margin-right: 0;
}
.attachment {
  color: #2165f9;
  cursor: pointer;
  text-decoration: underline;
  margin-right: 8px;
}
.draw-body {
  padding: 12px;
}
.frame {
  height: calc(80vh - 40px);
  width: 900px;
  /deep/ .ck-dialog-container {
  }
  top: 1vh !important;
}
.upload-file-wrap {
  display: flex;
  flex-wrap: wrap;
}
</style>
